<template>
	<view class="me-tabs">
		<scroll-view :id="viewId" :scroll-left="scrollLeft" scroll-x scroll-with-animation :scroll-animation-duration="500">
			<view class="tab-view" :style="{ height: `${tabheight}rpx` }">
				<view class="view-content" v-for="(tab, i) in TABS_ARRAY" :class="{ active: value === i }" :key="i" :style="{ width: `${tab.width}rpx` }" @click="tabClick(i)">
					<view class="toitem">
						<text>{{ getTabName(tab) }}</text>
						<block v-if="tab.num > 0">
							<view class="isdot" v-if="dots_switch"></view>
							<view class="textlength" v-if="number_switch">
								{{ judgeNum(tab.num) }}
							</view>
						</block>
					</view>
				</view>
				<view class="tabs-line" :style="[line_style]" v-if="TABS_INFO.length > 0"></view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import storeMixin from '@/store/storeMixin';
export default {
	mixins: [storeMixin],
	props: {
		tabs: {
			//支持格式: ['全部', '待付款'] 或 [{name:'全部'}, {name:'待付款'}]
			type: Array,
			default() {
				return [];
			},
		},
		nameKey: {
			//取name的字段
			type: String,
			default: 'title',
		},
		value: {
			//当前显示的下标 (使用v-model语法糖: 1.props需为value; 2.需回调input事件)
			type: [String, Number],
			default: 0,
		},
		//比例
		ratio: {
			type: [String, Number],
			default: 1,
		},
		//高度
		tabheight: {
			type: [String, Number],
			default: 100,
		},
		dots_switch: {
			type: [Boolean],
			default: false,
		},
		number_switch: {
			type: [Boolean],
			default: false,
		},
		show_number: {
			type: [Number],
			default: 2,
		},
		line_bot: {
			type: [Number],
			default: 8,
		},
	},
	data() {
		return {
			change_var: {},
			TABS_ARRAY: [], // 渲染用的数组
			TABS_INFO: [], // width left等参数
			viewId: 'id_' + Math.random().toString(36).substr(2, 16),
			scrollLeft: 0,
			warpWidth: 0,
			// itemHeight: 0,
		};
	},
	created() {
		this.init_pagedata('diynav');
		this.initComponent();
	},
	mounted() {
		// this.scrollCenter(); //滚动到当前下标
	},
	computed: {
		isScroll() {
			return this.tabs && this.tabs.length;
		},

		line_style() {
			let width = 0;
			let left = 0;
			let bottom = `${this.line_bot}rpx`;
			if (this.TABS_INFO.length > 0) {
				if (this.objJudge(this.TABS_INFO[this.value].show_width)) {
					width = `${this.TABS_INFO[this.value].show_width}rpx`;
				}

				if (this.objJudge(this.TABS_INFO[this.value].show_width)) {
					left = `${this.TABS_INFO[this.value].show_left}rpx`;
				}
			}
			return { width, left, bottom };
		},
	},

	methods: {
		async initComponent() {
			let _this = this;
			_this.TABS_ARRAY = await _this.initTabsArray();
			_this.TABS_INFO = await _this.initTabsInfo();
			_this.scrollCenter();
			// console.log(JSON.stringify(_this.TABS_INFO));
		},
		initTabsArray() {
			let _this = this;
			// _this.itemHeight = _this.pxTorpx(_this.tabheight);
			return new Promise(resolve => {
				setTimeout(() => {
					let query = uni.createSelectorQuery().in(_this);
					query = query.in(_this);
					query.select(`#${_this.viewId}`)
						// '.me-tabs'
						.boundingClientRect(data => {
							let INIT_TAB = _this.tabs.map(item => {
								item['width'] = _this.pxTorpx(data.width / _this.show_number);
								item['left_diff'] = data.left;
								return item;
							});
							_this.warpWidth = data.width;
							resolve(INIT_TAB);
						})
						.exec();
				}, 20);
			});
		},

		initTabsInfo() {
			let _this = this;
			return new Promise((resolve, reject) => {
				setTimeout(() => {
					let view = uni.createSelectorQuery().in(_this);
					view = view.in(_this);
					view.selectAll('#' + _this.viewId + ' .toitem')
						.boundingClientRect(res => {
							res.forEach((item, index) => {
								// 父级容器不是占满的750的话 left会有值
								item['left_diff'] = _this.TABS_ARRAY[index].left_diff || 0;
								item.left += (item.width * (1 - _this.ratio)) / 2 - item['left_diff'];
								item.width = item.width * _this.ratio;
								_this.$set(item, 'show_width', `${_this.pxTorpx(item.width)}`);
								_this.$set(item, 'show_left', `${_this.pxTorpx(item.left + item.width / 2)}`);
							});
							// console.log(res);
							_this.$emit('settab', _this.tabheight);
							resolve(res);
						})
						.exec();
				}, 50);
			});
		},

		async scrollCenter() {
			if (!this.isScroll) return;
			const tab = this.TABS_INFO[this.value];
			let diff = 0;
			if (tab) {
				diff = tab.left + tab.width / 2 - this.warpWidth / 2;
			}
			this.scrollLeft = diff;
			// #ifdef MP-TOUTIAO
			this.scrollTimer && clearTimeout(this.scrollTimer);
			this.scrollTimer = setTimeout(() => {
				//字节跳动小程序,需延时再次设置scrollLeft,否则tab切换跨度较大时不生效
				this.scrollLeft = Math.ceil(diff);
			}, 400);
			// #endif
		},
		judgeNum(n) {
			return n > 99 ? '99+' : n;
		},
		getTabName(tab) {
			return typeof tab === 'object' ? tab[this.nameKey] : tab;
		},
		tabClick(i) {
			if (this.value != i) {
				this.$emit('input', i);
				this.$emit('change', i);
			}
		},
	},
	watch: {
		value() {
			this.scrollCenter(); // 水平滚动到中间
		},
	},
};
</script>

<style lang="scss">
.me-tabs {
	width: 100%;
	box-sizing: border-box;
	overflow-y: hidden;
	z-index: 9;

	.tab-view {
		position: relative;
		white-space: nowrap;
		display: flex;
		.view-content {
			flex-shrink: 0;
			display: inline-flex;
			align-items: center;
			justify-content: center;
			line-height: 1.4;
			position: relative;
			text-align: center;
			padding: 0 28rpx;
			font-size: 32rpx;
			color: #a6aab3;

			&.active {
				font-weight: 700;
				color: #2e3443;
			}

			.toitem {
				position: relative;
				--color: #fe5656;
			}
		}
	}

	.isdot {
		position: absolute;
		left: 100%;
		top: 4rpx;
		transform: translate(4rpx, 0);
		width: 12rpx;
		height: 12rpx;
		border-radius: 50%;
		background-color: var(--color);

		-webkit-border-radius: 50%;
		-moz-border-radius: 50%;
		-ms-border-radius: 50%;
		-o-border-radius: 50%;
	}

	.textlength {
		position: absolute;
		left: 100%;
		top: 50%;
		transform: translate(7rpx, -50%);
		padding: 0 8rpx;
		height: 28rpx;
		line-height: 28rpx;
		background: #fe5656;
		border-radius: 14rpx;

		font-size: 24rpx;
		font-weight: 400;
		color: #ffffff;
	}

	//选中tab的线
	.tabs-line {
		z-index: 1;
		position: absolute;

		width: 0;
		height: 8rpx;
		border-radius: 4rpx;
		transform: translateX(-50%);
		transition: left 0.5s, width 0.5s;
		background: #333333;
	}
}
</style>
